package com.cvte.shop.exception.adaper;

import com.cvte.csb.core.interfaces.vo.RestResponse;
import com.cvte.csb.web.rest.ResponseFactory;
import com.cvte.shop.exception.BaseBusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author DaiShubo
 * @version 1.0
 * @description 异常处理类
 * @createTime 2020/7/29 4:18 下午
 * @since 1.7
 **/
@Slf4j
@RestControllerAdvice
public class ExceptionHandlerAdper {

    /**
     * 业务异常处理
     * @param e
     * @return RestResponse
     */
    @ExceptionHandler({BaseBusinessException.class})
    public RestResponse businessExceptionHandler(HttpServletRequest request, BaseBusinessException e) throws BaseBusinessException {
        return ResponseFactory.buildResult(e.getMessage(),e.getStatus(),null);
    }

    /**
     *
     * @param e
     * @return
     */
//    @ExceptionHandler(Exception.class)
//    public  RestResponse handlerException(Exception e) {
//
//        if (e instanceof HttpRequestMethodNotSupportedException){
//
//            log.warn("HttpRequestMethodNotSupportedException:{}",e.getMessage());
//            return ResponseFactory.buildResult(e.getMessage(),"500",null);
//        }else if (e instanceof MethodArgumentNotValidException){
//
//            List<ObjectError> list = ((MethodArgumentNotValidException)e).getBindingResult().getAllErrors();
//            StringBuffer buffer = new StringBuffer();
////            list.forEach((error) -> {
////                if(error instanceof FieldError) {
////                    buffer.append(((FieldError)error).getField()).append(":");
////                }
////                buffer.append(error.getDefaultMessage()).append(",");
////            });
//            log.warn("参数异常:{},异常参数:{}",e.getMessage(),buffer.toString());
//            return ResponseFactory.buildResult(buffer.toString(),"500",null);
//        }else if (e instanceof HttpMessageNotReadableException){
//
//            log.warn("参数异常：{}",e.getMessage());
//            return ResponseFactory.buildResult("please check your request body!","500",null);
//        }else if (e instanceof MethodArgumentTypeMismatchException){
//
//            log.warn("参数异常：{}",e.getMessage());
//            return ResponseFactory.buildResult("please check your parameter type!","500",null);
//        }else{
//            log.warn("参数异常：{}",e.getMessage());
//            return ResponseFactory.buildResult("系统异常","500",null);
//        }
//
//
//    }

}
